#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-sshd
# REQUIRE: FILESYSTEMS
# BEFORE: openssh

. /etc/rc.subr

#
# TODO: this is really just a place holder for the moment....
#
generate_sshd()
{
    local IFS="|"
    local f="ssh_bindiface ssh_tcpport ssh_rootlogin ssh_passwordauth ssh_kerberosauth ssh_tcpfwd ssh_compression ssh_sftp_log_level ssh_sftp_log_facility"
    eval local $f
    local sf=$(var_to_sf $f)
    local cmd cfg
    cfg=/usr/local/etc/ssh/sshd_config

    if [ ! -d /root/.ssh ]; then
        mkdir -p /root/.ssh
    fi

    RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
    trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT
    
    local options=$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT ssh_options FROM services_ssh ORDER BY -id LIMIT 1")
    ${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} \
        "SELECT $sf FROM services_ssh ORDER BY -id LIMIT 1" | \
        while eval read -r $f; do
            ssh_sftp_log_level=${ssh_sftp_log_level:-"ERROR"}
            ssh_sftp_log_facility=${ssh_sftp_log_facility:-"AUTH"}
            cat > $cfg << __EOF__
Subsystem       sftp    /usr/libexec/sftp-server -l ${ssh_sftp_log_level} -f ${ssh_sftp_log_facility}
__EOF__
            if ! echo $options | grep -q "Protocol"; then
                echo "Protocol 2" >> $cfg
            fi

            if ! echo $options | grep -q "UseDNS"; then
                echo "UseDNS no" >> $cfg
            fi

            if ! echo $options | grep -q "ChallengeResponseAuthentication"; then
                echo "ChallengeResponseAuthentication no" >> $cfg
            fi

            if ! echo $options | grep -q "ClientAliveCountMax"; then
                echo "ClientAliveCountMax 3" >> $cfg
            fi

            if ! echo $options | grep -q "ClientAliveInterval"; then
                echo "ClientAliveInterval 15" >> $cfg
            fi

            if ! echo "$options"| grep -q "NoneEnabled"; then
                echo "NoneEnabled yes" >> $cfg
            fi

            if ! echo "$options"| grep -q "VersionAddendum"; then
                echo "VersionAddendum none" >> $cfg
            fi

            # Add aes128-cbc by default. See #20044
            if ! echo "$options"| grep -qi "Ciphers "; then
                echo "Ciphers +aes128-cbc" >> $cfg
            fi

            if [ "$ssh_tcpport" -gt 0 ]; then
                echo "Port $ssh_tcpport" >> $cfg
            fi
            if [ -n "$ssh_bindiface" ]; then
                echo "ListenAddress 127.0.0.1" >> $cfg
                echo $ssh_bindiface|awk -F ',' '{for(i=1; i<=NF; ++i) print $i}' | while read -r iface; do
                    ifconfig ${iface} inet |  awk '/inet /{print $2}' 2> /dev/null | while read -r bindip; do
                        echo "ListenAddress ${bindip}" >> $cfg
                    done
                    ifconfig ${iface} inet6 |  awk '/inet6 /{print $2}' 2> /dev/null | while read -r bindip; do
                        echo "ListenAddress ${bindip}" >> $cfg
                    done
                done
            fi

            if [ "$ssh_rootlogin" = 1 ]; then
                echo "PermitRootLogin yes" >> $cfg
            else
                echo "PermitRootLogin without-password" >> $cfg
            fi
            if [ "$ssh_tcpfwd" = 1 ]; then
                echo "AllowTcpForwarding yes" >> $cfg
            else
                echo "AllowTcpForwarding no" >> $cfg
            fi
            if [ "$ssh_compression" = 1 ]; then
                echo "Compression delayed" >> $cfg
            else
                echo "Compression no" >> $cfg
            fi
            if [ "$ssh_passwordauth" = 1 ]; then
                echo "PasswordAuthentication yes" >> $cfg
            fi
            if [ "$ssh_kerberosauth" = 1 ]; then
                echo "GSSAPIAuthentication yes" >> $cfg
            fi
            ssh_pubkeyauth=1                # Missing in schema
            if [ "$ssh_pubkeyauth" = 1 ]; then
                echo "PubkeyAuthentication yes" >> $cfg
            fi
            
            echo $options >> $cfg
    done
    
    # Generate a passwordless key-pair for automatic replication
    if [ ! -d /data/ssh ]; then
        mkdir -m 755 /data/ssh
    fi
    if [ ! -e /data/ssh/replication ]; then
        /usr/local/bin/ssh-keygen -qt rsa -N "" -C "Key for replication" -b 2048 -f /data/ssh/replication
    fi
    ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT ssh_remote_hostkey FROM storage_replremote" > /usr/local/etc/ssh/ssh_known_hosts

    # extract the saved host keys from the database.
    for i in "ssh_host_key" "ssh_host_key.pub" "ssh_host_dsa_key" "ssh_host_dsa_key.pub" "ssh_host_dsa_key-cert.pub" "ssh_host_ecdsa_key" "ssh_host_ecdsa_key.pub" "ssh_host_ecdsa_key-cert.pub" "ssh_host_rsa_key" "ssh_host_rsa_key.pub" "ssh_host_rsa_key-cert.pub" "ssh_host_ed25519_key" "ssh_host_ed25519_key.pub" "ssh_host_ed25519_key-cert.pub"
    do
        column=`echo ${i} | tr ".-" "_"`
        _tmp=`${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT ${column} from services_ssh"`
        _tmpx=`echo ${_tmp} | tr '\n' '1'`
        if ! [ "${_tmpx}" = "1" ] ; then
            echo ${_tmp} | /usr/local/bin/base64 -d > /usr/local/etc/ssh/${i}
        fi
    done
    chmod 600 /usr/local/etc/ssh/ssh_host_key /usr/local/etc/ssh/ssh_host_dsa_key /usr/local/etc/ssh/ssh_host_ecdsa_key /usr/local/etc/ssh/ssh_host_rsa_key /usr/local/etc/ssh/ssh_host_ed25519_key 2>/dev/null
}

name="ix-sshd"
start_cmd='generate_sshd'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
